import { defineStore } from "pinia";
import { ref, shallowRef } from "vue";
import { getInfo, getRouters, UserInfoResponse } from "@/api/user.ts";
import { getMenuModule, getRouterModule } from "@/router/router-modules.ts";
import { homeRoutes } from "@/router";
import { IMeta, IRouter, ITagsViewRouter } from "@/utils/types/TMenu.ts";
import { RouteLocationNormalizedLoaded } from "vue-router";
import { IUser } from "@/utils/types/IUser.ts";

export const useUserStore = defineStore("user", () => {
  const userInfo = shallowRef<IUser>();
  const routerData = shallowRef();
  const menuData = shallowRef<IRouter[]>([]);
  const permissionsList = shallowRef<string[]>([]);
  const tabsList = ref<ITagsViewRouter[]>([
    {
      fullPath: "/home",
      meta: { title: "工作台", icon: "icon-ic_menu_home" },
    },
  ]);
  const collapsed = shallowRef(false);

  // 获取路由
  const generateDynamicRoutes = async () => {
    const { data } = await getRouters();
    data.unshift(homeRoutes);
    menuData.value = getMenuModule(data);
    routerData.value = getRouterModule(data);
    return routerData.value;
  };

  // 获取用户信息
  const getUserInfo = async () => {
    const { permissions, user }: UserInfoResponse = await getInfo();
    userInfo.value = user;
    permissionsList.value = permissions;
  };

  // tags-view
  // 添加tagsview
  const addTags = (route: IRouter | RouteLocationNormalizedLoaded) => {
    // 添加标签页
    const r: ITagsViewRouter = {
      fullPath: route.fullPath,
      meta: {
        title: route.meta.title,
        icon: route.meta.icon,
      } as IMeta,
    };
    const isExists = tabsList.value.some(
      (item: ITagsViewRouter) => item.fullPath === r.fullPath,
    );
    if (!isExists) {
      tabsList.value.push(r);
    }
  };
  const closeCurrentTag = (route: ITagsViewRouter) => {
    // 关闭当前页
    const index = tabsList.value.findIndex(
      (item: ITagsViewRouter) => item.fullPath === route.fullPath,
    );
    tabsList.value.splice(index, 1);
  };
  const closeAllTags = () => {
    tabsList.value = tabsList.value.filter(
      (_item: ITagsViewRouter, idx: number) => idx === 0,
    );
  };
  const closeLeftTags = (index: number) => {
    tabsList.value = tabsList.value.filter(
      (_item: ITagsViewRouter, idx: number) => idx >= index || idx === 0,
    );
  };
  const closeRightTags = (index: number) => {
    tabsList.value = tabsList.value.filter(
      (_item: ITagsViewRouter, idx: number) => idx <= index || idx === 0,
    );
  };

  // collapsed
  const toggleCollapsed = () => {
    collapsed.value = !collapsed.value;
  };

  return {
    userInfo,
    permissionsList,
    routerData,
    menuData,
    getUserInfo,
    generateDynamicRoutes,
    tabsList,
    addTags,
    closeCurrentTag,
    closeAllTags,
    closeLeftTags,
    closeRightTags,
    collapsed,
    toggleCollapsed,
  };
});
